package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * The type Jwt util.
 */
public class JWTUtil {
    private String key;
    private long ttl;

    /**
     * Gets key.
     *
     * @return the key
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets key.
     *
     * @param key the key
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * Gets ttl.
     *
     * @return the ttl
     */
    public long getTtl() {
        return ttl;
    }

    /**
     * Sets ttl.
     *
     * @param ttl the ttl
     */
    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成JWT
     *
     * @param id      the id
     * @param subject the subject
     * @param roles   the roles
     * @return string string
     * @paramid
     * @paramsubject
     */
    public String createJWT(String id, String subject, Object roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles",
                        roles);
        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     *
     * @param jwtStr the jwt str
     * @return claims claims
     * @paramjwtStr
     */
    public Claims parseJWT(String jwtStr) {
        return Jwts.parser()
                .setSigningKey("secrect")
                .parseClaimsJws(jwtStr)
                .getBody();
    }
}
